﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using EssentialWebFramework.Models.Framework;
using NLog;

namespace EssentialWebFramework.Utilities
{
    /// <summary>
    /// 邮件 实用工具类
    /// </summary>
    public class MailUtils
    {
        /// <summary>
        /// logger
        /// </summary>
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();


        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="toAddress"></param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static async Task<ExecResult> SendEmail(string toAddress, string title, string content)
        {
            var mailCfg = GlobalConfig.Setting.Mail;

            try
            {
                MailMessage message = new MailMessage();

                message.To.Add(toAddress);
                message.From = new MailAddress(mailCfg.FromAddress, mailCfg.DisplayName, Encoding.UTF8);

                message.Subject = title;
                message.SubjectEncoding = Encoding.UTF8;

                message.Body = content;
                message.BodyEncoding = Encoding.UTF8;

                SmtpClient smtpClient = new SmtpClient();

                smtpClient.EnableSsl = true;
                smtpClient.Credentials = new NetworkCredential(mailCfg.FromAddress, mailCfg.SecretKey);
                smtpClient.Host = mailCfg.SMTPServer;

                smtpClient.Timeout = 10_000;

                await smtpClient.SendMailAsync(message);
                return ExecResult.ExecSuccess;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return ExecResult.Error("发送邮件失败，请联系管理员");
            }
        }
    }
}
